<template>
  <el-dialog
    :visible.sync="visible"
    width="80%"
    custom-class="default-dialog"
    :close-on-click-modal="false"
    @close="cancel"
    append-to-body
    v-dialogDrags
  >
    <div slot="title">
      <img v-if="type" :src="require(`@/assets/img/${type}.png`)" alt="" />
      <span>{{ title }} </span>
    </div>
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-width="120px"
      class="dialog-form"
      :disabled="type == 'view'"
    >
      <el-row :gutter="5">
        <el-col :span="8">
          <el-form-item label="年份" prop="year">
            <el-date-picker
              :disabled="isYearDisabled"
              style="width: 130px"
              size="small"
              v-model="form.year"
              type="year"
              placeholder="选择时间"
              format="yyyy"
              value-format="yyyy"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="河湖名称" prop="riverId">
            <el-select
              :disabled="isHeHuNameDisabled"
              size="small"
              v-model="form.riverId"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in rvOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="总得分" prop="score">
            <el-input
              disabled
              size="small"
              v-model="form.score"
              placeholder="总得分"
            ></el-input>
          </el-form-item>
        </el-col> </el-row
      ><!--总项-->
      <el-row :gutter="10">
        <el-col :span="12" :gutter="10">
          <span style="font-size: 20px">分项指标得分</span>
        </el-col>
      </el-row>
      <el-row :gutter="5"
        ><!--指标分项-->
        <el-col :span="24">
          <el-table :data="list_ev" :height="'300px'" style="width: 100%">
            <el-table-column
              width="120px"
              show-overflow-tooltip
              prop="name"
              label="指标名称"
              align="center"
            ></el-table-column>
            <el-table-column
              width="120px"
              show-overflow-tooltip
              prop="typeName"
              label="指标类型"
              align="center"
            ></el-table-column>
            <el-table-column
              width="60px"
              prop="totalScore"
              label="满分"
              align="center"
            ></el-table-column>
            <el-table-column
              width="80px"
              prop="subCore"
              label="得分"
              align="center"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.subCore"
                  @input="handleInputChange(scope.$index, scope.row)"
                  size="small"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              width="160px"
              show-overflow-tooltip
              prop="attribute"
              label="性质"
              align="center"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="criterion"
              label="准测层"
              align="center"
            ></el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="metrics"
              label="指标层"
              align="center"
            ></el-table-column>
            <el-table-column
              width="80px"
              show-overflow-tooltip
              prop="source"
              label="来源"
              align="center"
            ></el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row :gutter="5"
        ><!--复苏目标-->
        <el-col :span="24">
          <span style="font-size: 20px">复苏目标</span>
          <el-button
            type="text"
            fixed="right"
            icon="el-icon-plus"
            title="添加"
            @click="addTarget"
          ></el-button>
        </el-col>
      </el-row>
      <el-row :gutter="5">
        <el-table :data="recoveryTarget" style="width: 100%; height: 180px">
          <el-table-column
            width="120px"
            type="index"
            prop="sortIndex"
            label="展示顺序"
            align="center"
          ></el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="target"
            label="目标"
            align="center"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.target" size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            width="60px"
            fixed="right"
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                title="删除"
                @click="delTarget(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>

      <el-row :gutter="5"
        ><!--复苏目标-->
        <el-col :span="24">
          <span style="font-size: 20px">任务及措施</span>
          <el-button
            type="text"
            icon="el-icon-plus"
            style="padding-right: 10px"
            title="添加"
            @click="addTaskAndMeasures"
          ></el-button>
        </el-col>
      </el-row>
      <el-row :gutter="5">
        <el-table :data="taskAndMeasures" style="width: 100%; height: 180px">
          <el-table-column
            width="120px"
            type="index"
            prop="sortIndex"
            label="展示顺序"
            align="center"
          ></el-table-column>
          <el-table-column
            width="240px"
            show-overflow-tooltip
            prop="task"
            label="任务"
            align="center"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.task" size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            show-overflow-tooltip
            prop="measure"
            label="措施"
            align="center"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.measure" size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            width="140px"
            prop="deadline"
            label="截至时间"
            align="center"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.deadline" size="small"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            width="60px"
            fixed="right"
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                title="删除"
                @click="delTaskAndMeasures(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-form>

    <span slot="footer">
      <el-button size="small" @click="cancel">取 消</el-button>
      <el-button size="small" v-if="type != 'view'" type="primary" @click="sure"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import { Message } from "element-ui";

export default {
  data() {
    return {
      visible: false,
      isYearDisabled:false,
      isHeHuNameDisabled:false,
      title: "",
      form: {
        id: "",
        year: "",
        riverId: "",
        score: "0",
      },
      list_ev: [],
      subItemScore: [],
      recoveryTarget: [],
      taskAndMeasures: [],
      rvOptions: [],
      rules: {
        year: [{ required: true, message: "请选择年份", trigger: "blur" }],
        riverId: [
          { required: true, message: "请选择河湖名称", trigger: "blur" },
        ],
      },
      type: "",
    };
  },
  mounted() {
    this.getparams();
  },
  computed: {},
  methods: {
    handleInputChange(index, row) {
      if (
        row.subCore &&
        row.totalScore &&
        Number(row.subCore) > Number(row.totalScore)
      ) {
        this.$message.error("分项得分不能大于满分！");
        row.subCore = 0; // 清空不符合条件的值
      }
      let sum = 0;
      this.list_ev.forEach((item) => {
        if (item.subCore) {
          sum += +item.subCore;
        }
      });
      this.form.score = sum;
    },
    getparams() {
      this.$api.getRevivingRiverName({ keywords: "" }).then((res) => {
        if (res && res.code == 200) {
          this.rvOptions = res.data || [];
        }
      });
    },
    showModal(type, row) {
      this.visible = true;
      this.type = type;
      if (type == "add") {
        this.title = "新增";
        this.form = {};
        this.isYearDisabled=false
        this.isHeHuNameDisabled=false
        this.subItemScore = [];
        this.recoveryTarget = [];
        this.taskAndMeasures = [];
        this.getInfoItem();
      } else if (type == "edit") {
        this.title = "编辑";
        this.isYearDisabled=true
        this.isHeHuNameDisabled=true
        this.getInfoInit(row.id);
      } else if (type == "view") {
        this.title = "详情";
        this.isYearDisabled=true
        this.isHeHuNameDisabled=true
        this.getInfoInit(row.id);
      }
    },
    getInfoItem() {
      this.$api.getAllHuMetrics({}).then((res) => {
        if (res && res.code == 200) {
          this.list_ev = res.data || [];
           this.list_ev.forEach(e => {
            switch (e.type){
              case "river":
                e.typeName ="河流类型";
                break;
              case "lake":
                e.typeName="湖泊类型";
                break;
              case "manage":
                e.typeName ="管理类型";
                break;
            }
           })
        }
      });
    },
    // 详情
    getInfoInit(id) {
      this.$api.getHeHuScoring({ id: id }).then((res) => {
        if (res && res.code == 200) {
          let data = res.data || {};
          this.form = data;
          this.subItemScore = data.subItemScore || [];
          this.recoveryTarget = data.recoveryTarget || [];
          this.taskAndMeasures = data.taskAndMeasures || [];

          //获取指标项
          this.$api.getAllHuMetrics({}).then((res) => {
            if (res && res.code == 200) {
              this.list_ev = [];
              let list = res.data || []
              let sub = this.subItemScore || []
              /*console.info("----------------sub长度："+sub.length)
              for(var j=0;j<sub.length;j++){
                  let isexist=false
                  let item = null
                  console.info("----------------"+sub[j].metricsId)
                  for(var m=0;m<list.length;m++){
                    if(list[m].id===sub[j].metricsId){
                      console.info("----------------存在"+sub[j].metricsId)
                      list[m].subCore=sub[j].score
                      this.list_ev.push(list[m]);
                      isexist=true
                    }
                  }
                  if(!isexist){
                    console.info("----------------不存在"+sub[j].metricsId)
                  }
              }*/

              for(var i=0;i<list.length;i++){
                list[i].subCore = this.getItemScore(list[i].criterion,list[i].id,sub)
                this.list_ev.push(list[i]);
              }
            }
          });
        }
      });
    },
    getItemScore(name,id,sub){
      for(var j=0;j<sub.length;j++){
        if(id === sub[j].metricsId){
          return  sub[j].score
        }
      }
      return 0
    },
    // 确定
    sure() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          //分项评分
          let ev = [];
          this.list_ev.forEach((e) => {
            let subItemScore = {
              metricsId: e.id,
              score: e.subCore || 0,
            };
            ev.push(subItemScore);
          });
          //目标
          let tar = [];
          console.log(`recoveryTarget：${this.recoveryTarget.length}`);
          for (let i = 0; i < this.recoveryTarget.length; i++) {
            let e = this.recoveryTarget[i]
            if (e.target === "") {
              Message.error("请填写复苏目标!");
              return;
            }
            let item = {
              sortIndex: e.sortIndex,
              target: e.target || "",
            };
            tar.push(item);
          }
          //任务及方法
          let task = [];
          for(let i=0;i<this.taskAndMeasures.length;i++){
            let e = this.taskAndMeasures[i]
            if (e.task  === "") {
              Message.error("任务及措施请填写任务!");
              return;
            }
            if (e.measure  === "") {
              Message.error("任务及措施请填写措施!");
              return;
            }
            if (e.deadline  === "") {
              Message.error("任务及措施请填写截至时间!");
              return;
            }

          }
          this.taskAndMeasures.forEach((e) => {
            let item = {
              deadline: e.deadline || "",
              measure: e.measure || "",
              sortIndex: e.sortIndex,
              task: e.task || "",
            };
            task.push(item);
          });

          let param = {
            riverId: this.form.riverId,
            score: this.form.score,
            year: this.form.year,
            subItemScore: ev,
            recoveryTarget: tar,
            taskAndMeasures: task,
          };
          if (this.type == "add") {
            //保存
            this.$api.addHeHuScoring(param).then((res) => {
              if (res && res.code == 200) {
                this.$notify.success({
                  title: "成功",
                  message: "数据保存成功",
                });
                this.visible = false;
                this.$emit("listInit");
              }
            });
          } else if (this.type == "edit") {
            let params = Object.assign({}, param, {
              id: this.form.id,
            });
            this.$api.updateHeHuScoring(params).then((res) => {
              if (res && res.code == 200) {
                this.$notify.success({
                  title: "成功",
                  message: "数据保存成功",
                });
                this.visible = false;
                this.$emit("listInit");
              }
            });
          }
        }
      });
    },
    // 取消
    cancel() {
      this.visible = false;
      this.$refs["form"].resetFields();
    },
    //添加目标
    addTarget() {
      this.recoveryTarget.push({
        sortIndex: this.recoveryTarget.length + 1,
        target: "",
      });
    },
    //添加任务及措施
    addTaskAndMeasures() {
      this.taskAndMeasures.push({
        sortIndex: this.taskAndMeasures.length + 1,
        task: "",
        measure: "",
        deadline: "",
      });
    },
    // 删除
    delTarget(row) {
      this.$confirm("确认删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //this.recoveryTarget.splice(row.sortIndex,1)
          this.recoveryTarget.pop();
        })
        .catch(() => {});
    },
    // 删除
    delTaskAndMeasures(row) {
      this.$confirm("确认删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //this.taskAndMeasures.splice(row.sortIndex,1)
          this.taskAndMeasures.pop();
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="less" scoped>
.el-form-item__label {
  width: 150px;
}

.grid-create {
  top: 7.5rem;
  position: absolute;
  z-index: 10;
  width: 40rem;
  height: 84%;
  background: #fff;
  background-size: 100% 100%;
  right: 0.4rem;
}
</style>
